﻿// (c) Copyright Damian Mehers http://damianblog.com/
// This source is subject to the Microsoft Public License.
// See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx.
// All other rights reserved.

using System;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;

namespace MceFM.Last.MediaPlayer {
  internal class MediaPlayerInfo {
    private readonly object initializedLock = new object();
    private bool initialized;
    private Exception initializedException;
    private MediaPlayerForm mediaPlayerForm;

    // public event EventHandler<NewSongPlayingEventArgs> NewSongPlaying;
    //internal event EventHandler<TrackTimeEventArgs> TrackTime;
    public event EventHandler<TrackStoppedOrStartedEventArgs> TrackStoppedOrStarted;


    public void Start() {
      Thread thread = new Thread(ThreadEntry);
      thread.IsBackground = true;
      thread.SetApartmentState(ApartmentState.STA);
      thread.Start();
      WaitUntilInitialized();
    }

    private void WaitUntilInitialized() {
      lock(initializedLock) {
        while(!initialized) {
          Monitor.Wait(initializedLock);
        }
      }
      if(initializedException != null) {
        throw initializedException;
      }
    }


    private void ThreadEntry() {
      try {
        mediaPlayerForm = new MediaPlayerForm();
        //mediaPlayerForm.NewSongPlaying += NewSongPlayingHandler;
        //mediaPlayerForm.TrackTime += TrackTimeHandler;
        mediaPlayerForm.TrackStoppedOrStarted += TrackStoppedOrStartedHandler;
        mediaPlayerForm.Show();
      } catch(Exception ex) {
        Trace.TraceError("Error installing windows hook", ex);
        initializedException = ex;
      } finally {
        initialized = true;
        lock(initializedLock) {
          Monitor.Pulse(initializedLock);
        }
      }

      Application.Run();
    }

    private void TrackStoppedOrStartedHandler(object sender, TrackStoppedOrStartedEventArgs e) {
      EventHandler<TrackStoppedOrStartedEventArgs> tmp = TrackStoppedOrStarted;
      if (tmp != null) {
        tmp(this, e);
      }
    }

    //private void TrackTimeHandler(object sender, TrackTimeEventArgs e) {
    //  EventHandler<TrackTimeEventArgs> tmp = TrackTime;
    //  if(tmp != null) {
    //    tmp(this, e);
    //  }
    //}

    //private void NewSongPlayingHandler(object sender, NewSongPlayingEventArgs e) {
    //  EventHandler<NewSongPlayingEventArgs> tmp = NewSongPlaying;
    //  if(tmp != null) {
    //    tmp(this, e);
    //  }
    //}

    public void QueueUrl(string url, bool first) {
      mediaPlayerForm.QueueUrl(url, first);
    }

    public void Next() {
      mediaPlayerForm.Next();
    }

    public void StopPlaying() {
      mediaPlayerForm.StopPlaying();
    }
  }
}